from rest_framework import serializers
from django.contrib.auth import authenticate
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    token = serializers.CharField(read_only=True)
    user_id = serializers.IntegerField(read_only=True)

    def validate(self, attrs):

        user = authenticate(**attrs)

        if not user:
            # 认证失败
            raise serializers.ValidationError('用户或密码错误')

        payload = jwt_payload_handler(user)
        jwt_token = jwt_encode_handler(payload)

        return {
            'user': user,
            'token': jwt_token
        }